package com.haojin.java;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @author .29.
 * @create 2022-04-16 22:10
 */
/*
RandomAccessFile的使用
1.RandomAccessFile直接继承于java.lang.Object类，实现了DataInput和DataOutput接口
2.RandomAccessFile既可以作为输入流，也可以作为输出流

3.如果RandomAccessFile作为输出流时，写出到的文件如果不存在，则执行过程中自动创建
  若写出到的文件存在，则会对原有文件内容从头开始覆盖

4.可以通过相关的操作，实现RandomAccessFile“插入”数据的效果。

 */
public class RandomAccessFileTest {
    @Test
    public void test(){
        RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;
        try {
            raf1 = new RandomAccessFile(new File("p.JPG"), "r");
            raf2 = new RandomAccessFile(new File("p1.JPG"), "rw");

            byte[] buffer= new byte[1024];
            int len;
            while((len = raf1.read(buffer)) != -1){
                raf2.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (raf1 != null) {
                try {
                    raf1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (raf2 != null) {
                try {
                    raf2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @Test
    public void test2(){
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile("hello.txt", "rw");

            raf.seek(3);
            raf.write("XYZ".getBytes());//覆盖的写入效果
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /*
    插入数据的效果：
     */
    @Test
    public void test3()   {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile("hello.txt", "rw");

            raf.seek(9);
            StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
            byte[] buffer = new byte[3];
            int len;
            while((len = raf.read(buffer)) != -1){
                builder.append(new String(buffer,0,len));
            }

            raf.seek(9);
            raf.write("XYZ".getBytes());
            raf.write(builder.toString().getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
